<template>
  <div class="item-detail">
    <van-nav-bar
      title="标题"
      left-text="返回"
      left-arrow
      @click-left="back"
    >
      <template #left>
        <van-icon name="arrow-left" size="20"/>
      </template>
    </van-nav-bar>

    <van-swipe :autoplay="3000">
      <van-swipe-item v-for="(image, index) in goods.info.gallery" :key="index">
        <img v-lazy="image" width="100%">
      </van-swipe-item>
    </van-swipe>
    <div class="card">
      <div>
        <div>
          <span class="pro-price"><span class="price-unit">¥</span>{{ goods.info.retailPrice }}</span>
          <span class="pro-market-price">¥{{ goods.info.counterPrice }}</span>
        </div>
        <div class="pro-title">{{ goods.info.name }}</div>

        <div class="pro-price-bottom">
          <span class="iconfont icon-recommend icon">推荐</span>
          <span class="iconfont icon-share icon">分享 </span>
        </div>
      </div>
    </div>
    <div class="card ">
      <div class="pro-attr-wrap" @click="showSkuPop">
        <span>选择</span>
        <div class="pro-attr-item">
          <div class="pro-attr-top">
            <span class="pro-attr-title">{{ specifications.join('/') }}</span>
            <van-icon name="arrow" size="10" class="pro-attr-right"/>
          </div>
          <div class="pro-attr-img-wrap">
            <img class="pro-attr-img" v-for="(item,index) in previewImage" :key="index"
                 :src="item" alt="">
            <span class="pro-attr-img-size">共{{ specifications.length }}种{{ specifications.join('') }}可选</span>
          </div>
        </div>

      </div>
      <div class="pro-attr-wrap margin-top-15">
        <span>发货</span>
        <div class=" pro-depository-wrap ">
          <div>
            <span class="pro-depository">浙江杭州</span>
            <span style="width:2px;height:10px; background: #f3f3f3;"></span>
            <span class="pro-depository">快递:包邮</span>
          </div>
          <van-icon name="arrow" size="10" class="pro-attr-right"/>
        </div>

      </div>

      <div class="pro-attr-wrap margin-top-15" @click="showAttrs=true">
        <span>参数</span>
        <div class=" pro-depository-wrap ">
          <span class="pro-depository">{{  attribute  }}</span>
          <van-icon name="arrow" size="10" class="pro-attr-right"/>
        </div>
      </div>
    </div>
    <div class="card ">

      <div>
        <span class="pro-assess">宝贝评价({{goods.comment.count}})</span>
        <div class="pro-assess-all">
          <span>查看全部</span>
          <van-icon name="arrow" size="10" color="#db3d3c"/>
        </div>
      </div>
      <ul>
        <li v-for="(item,index) in goods.comment.data" :key="index">
         <div class="comment-wrap">
           <div class="user-wrap">
             <van-image
               round
               width="1rem"
               height="1rem"
               :src="item.avatar"
             />
             <span class="nickname margin-left">{{hidenNick(item.nickname)}}</span>
           </div>
           <p class="nickname margin-top">{{item.content}}</p>
         </div>

        </li>
      </ul>
    </div>
    <van-divider
      :style="{ color: '#3f3f3f', borderColor: '#3f3f3f', padding: '0 120px',margin:'10px'}">
      宝贝详情
    </van-divider>
    <div class="card item_desc" v-html="goods.info.detail">
    </div>
    <van-goods-action>
      <van-goods-action-icon icon="home-o" text="主页" @click="toHome"/>
      <van-goods-action-icon icon="cart-o" text="购物车"  @click="addCar"/>
      <van-goods-action-icon icon="star" text="已收藏" color="#ff5000" v-if="goods.userHasCollect===1"
      @click="handleCollect(1)"/>
      <van-goods-action-icon icon="star-o" text="收藏" @click="handleCollect(0)"  v-else/>
      <van-goods-action-button type="warning" text="加入购物车" @click="addCar"/>
      <van-goods-action-button
        type="danger"
        text="立即购买"
        @click="buy"
      />
    </van-goods-action>

    <van-sku
      v-model="showSku"
      :sku="sku"
      :goods="skuGoods"
      :goods-id="goods.info.id"
      :hide-stock="sku.hide_stock"
      @buy-clicked="onBuyClicked"
      @add-cart="onAddCar"
    >
      <template #sku-actions="props" v-if="!isSelect">
        <div class="van-sku-actions">
          <van-button
            square
            size="large"
            type="danger"
            @click="props.skuEventBus.$emit('sku:buy')"
          >确认
          </van-button>
        </div>
      </template>
    </van-sku>
    <van-action-sheet v-model="showAttrs" title="属性" :closeable="true">
      <div class="content">
        <van-cell :center="true" v-for="(item,index) in goods.attribute" :key="index" >
          <van-row>
            <van-col span="8">{{item.attribute}}</van-col>
            <van-col span="16">{{item.value}}</van-col>
          </van-row>
        </van-cell>
      </div>
    </van-action-sheet>
  </div>
</template>

<script>
import {cartAdd, cartFastAdd, goodsDetail} from '../../api/items'
import _ from 'lodash'
import {Toast} from 'vant'
import {collectAddOrDelete} from '../../api/collect'

export default {
  name: 'detail',
  created () {
    this.initData()
  },
  computed: {
    attribute () {
      return this.goods.attribute.map(item => item.attribute).join(' ')
    },
    previewImage () {
      let imgList = []
      _.each(this.goods.specificationList, v => {
        _.each(v.valueList, vv => {
          let picUrl = vv.picUrl
          if (picUrl != null && picUrl !== 'undefined' && picUrl !== '') {
            imgList.push(picUrl)
          }
        })
      })
      return imgList
    },
    specifications () {
      return this.goods.specificationList.map(item => item['name'])
    }
  },
  methods: {
    hidenNick (text) {
      if (text.length > 2) {
        return text.substr(0, 1) + '**' + text.substr(text.length - 1, text.length)
      } else {
        return text
      }
    },
    handleCollect (type) {
      collectAddOrDelete({valueId: this.$route.params.id, type: type}).then(res => {
        if (this.goods.userHasCollect === 1) {
          this.goods.userHasCollect = 0
          this.$toast({
            message: '取消收藏成功',
            duration: 1500
          })
        } else {
          this.goods.userHasCollect = 1
          this.$toast({
            message: '收藏成功',
            duration: 1500
          })
        }
      })
    },
    initData () {
      goodsDetail({id: this.$route.params.id}).then(res => {
        this.goods = res.data.data
        this.skuAdapter()
      })
    },
    skuAdapter () {
      const tree = this.getSkuTree(this.goods.specificationList)
      const list = this.getSkuList()
      const skuInfo = {
        price: parseInt(this.goods.info.retailPrice), // 未选择规格时的价格
        stock_num: 0, // TODO 总库存
        collection_id: '', // 无规格商品skuId取collection_id，否则取所选sku组合对应的id
        none_sku: false, // 是否无规格商品
        hide_stock: true
      }
      this.sku = {
        tree,
        list,
        ...skuInfo
      }
      this.skuGoods = {
        title: this.goods.info.name,
        picture: this.goods.info.picUrl
      }
    },
    getSkuTree (data) {
      let specifications = []
      _.each(this.goods.specificationList, (v, k) => {
        let values = []
        _.each(v.valueList, vv => {
          vv.name = vv.value
          values.push({
            id: vv.id,
            name: vv.value,
            imUrl: vv.picUrl,
            previewImgUrl: vv.picUrl
          })
        })

        specifications.push({
          k: v.name,
          v: values,
          k_s: 's' + (~~k + 1)
        })
      })

      return specifications
    },
    getSkuList () {
      let skuList = []
      _.each(this.goods.productList, v => {
        let skuListObj = {}
        _.each(v.specifications, (specificationName, index) => {
          skuListObj['s' + (~~index + 1)] = this.findSpecValueIdByName(
            specificationName
          )
        })

        skuListObj.id = v.id
        skuListObj.price = v.price * 100
        skuListObj.stock_num = v.number
        skuList.push(skuListObj)
      })

      return skuList
    },
    findSpecValueIdByName (name) {
      let id = 0
      _.each(this.goods.specificationList, specification => {
        _.each(specification.valueList, specValue => {
          if (specValue.value === name) {
            id = specValue.id
          }
        })
        if (id !== 0) {

        }
      })
      return id
    },
    back () {
      this.$router.back()
    },
    toHome () {
      this.$router.replace('/')
    },
    showSkuPop () {
      this.isSelect = true
      this.showSku = true
    },
    addCar () {
      this.showSku = true
    },
    buy () {
      this.isBuy = true
      this.showSku = true
    },
    onAddCar (data) {
      cartAdd(data).then(res => {
        Toast('添加购物车成功')
        this.showSku = false
      })
    },
    onBuyClicked (skuData) {
      let data = {
        goodsId: skuData.goodsId,
        productId: skuData.selectedSkuComb.id,
        number: skuData.selectedNum
      }
      if (this.isBuy) {
        let that = this
        cartFastAdd(data).then(res => {
          let cartId = res.data.data
          that.showSku = false
          that.$router.push({name: 'confirm', params: {id: cartId}})
        })
      } else {
        this.onAddCar(data)
      }
      this.isBuy = false
    }
  },
  data () {
    return {
      showAttrs: false,
      showSku: false,
      isBuy: false,
      isSelect: false,
      isCar: false,
      goodsId: 111,
      previewCout: 0,
      sku: {},
      goods: {
        // 商品标题
        title: '',
        // 默认商品 sku 缩略图
        picture: ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.van-nav-bar .van-icon {
  color: #db3d3c;
}

.item_desc > > > img {
  max-width: 100%;
}
.nickname{
  font-size: 12px;
}
.margin-left{
  margin-left: 5px;
}
.margin-top{
  margin-top: 10px;
}
.user-wrap{
  display: flex;
  flex-direction: row;
  align-items: center;
}
.comment-wrap{
  padding: 10px 0;
}
.pro-price {
  color: #db3d3c;
  font-weight: bold;
  font-size: 20px;
}

.price-unit {
  margin: 2px;
  font-weight: normal;
  font-size: 18px;
}

.pro-market-price {
  margin-left: 5px;
  color: #999;
  font-size: 12px;
  text-decoration: line-through;
}

.pro-title {
  margin-top: 5px;
  font-weight: bold;
  font-size: 18px;
}

.pro-price-bottom {
  margin-top: 10px;
  display: flex;
  flex-direction: row;
  color: #3f3f3f;
  justify-content: space-around;
}

.pro-price-bottom span {
  text-align: center;
}

.icon {
  font-size: 10px;
}

.pro-attr-wrap {
  flex: 1;
  font-size: 12px;
  color: #999;
  display: flex;
}

.pro-attr-item {
  margin-left: 10px;
  flex: 1;
}

.pro-attr-top {
  justify-content: center;
  align-items: center;
  flex: 1;
}

.pro-attr-right {
  float: right;
}

.pro-attr-title {
  color: black;
}

.pro-attr-img {
  margin: 10px 10px 0 0;
  width: 30px;
  height: 30px;
}

.pro-attr-img-size {
  margin-top: 10px;
  background: #f3f3f3;
  padding: 5px;
  border-radius: 5px;
}

.pro-attr-img-wrap {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.divider {
  width: 1px;
}

.pro-depository {
  width: 70px;
  text-overflow :ellipsis; /*让截断的文字显示为点点。还有一个值是clip意截断不显示点点*/
  white-space :nowrap; /*让文字不换行*/
  overflow : hidden; /*超出要隐藏*/
  margin: 0 5px 0 5px;
  color: black;
}

.pro-depository-wrap {
  flex: 1;
  justify-content: space-between;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.margin-top-15 {
  margin-top: 15px;
}

.pro-assess {
  font-size: 14px;
  font-weight: bold;
}

.pro-assess-all {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  color: #db3d3c;
  font-size: 12px;
  float: right;
}
</style>
